package com.javaweb.config.websocket;

import java.io.IOException;
import java.util.LinkedList;

import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

/**
 * websocket在线广播
 * <p>
 * 使用：注入WebSocketOnlineBroadcastHandle即可
 * @author tank2140896
 */
@Component
@ServerEndpoint(value="/ws/onlineBroadcast") 
public class WebSocketOnlineBroadcastHandle {
	
	public static LinkedList<Session> client = new LinkedList<Session>();//如果是分布式部署的话，这里推荐采用redis进行存储替代
	
	@OnMessage
	public void onMessage(String message) {
		System.out.println("接收到的消息为："+message);
		for(Session session:client) {
			try {
				session.getBasicRemote().sendText(message);
			} catch (IOException e) {
				//do nothing
			}
		}
	}

	@OnOpen
	public void onOpen(Session session) {
		System.out.println("成功建立连接");
		client.add(session);
	}

	@OnClose
	public void onClose(Session session) {
		System.out.println("连接关闭");
	}
	
	@OnError
	public void onError(Throwable throwable){
		System.out.println(throwable.getMessage());
	}

}
